<?php
/**
 * Created by PhpStorm.
 * User: W
 * Date: 2019/1/7
 * Time: 10:44
 */

namespace app\sports_admin\model;


use think\Model;
use think\Db;
use think\Request;
use think\helper\Time;

class Homework extends Model
{
    protected $table = "homework";
    protected $pk    = "id";
    protected $autoWriteTimestamp = true;
    //班级名
    public function getClassName()
    {
        return $this->belongsTo("ClassModel","class_id","id");
    }
    //教师名
    public function getTeacherName()
    {
        return $this->belongsTo("Teacher","teacher_id","id");
    }
    //教案名
    public function getPlanName()
    {
        return $this->belongsTo("Plan","plan_id","id");
    }
    //作业内容
    public static function getHwContentAttr($values)
    {
        return htmlspecialchars_decode($values);
    }

    /**
     * @param $page 页数
     * @param $rows 每页显示条数
     * @param $sort 排序字段
     * @param $sortOrder 排序方式
     * @param $id 教师id
     * @param $date 作业发布日期
     * @return \think\response\Json
     */
    public static function homeworkList($page,$rows,$sort,$sortOrder,$id,$date)
    {
        //截取年月日
//        $year = substr($date,0,4);
//        $month = substr($date,5,2);
//        $day   = substr($date,8,2);
        $result = self::with("getClassName")
            ->where("teacher_id",$id)
            ->where(function($query)use($date){
                if(!empty($date)){
                    $time = explode('-',$date);
                    $time = getStartAndEndUnixTimestamp($time[0],$time[1],$time[2]);
                    $query->where("create_time",">",$time['start'])->where("create_time","<",$time['end']);
                }})
            ->order("{$sort}","{$sortOrder}")
            ->page($page)
            ->limit($rows)
            ->select();

        $total = self::with("getClassName")
            ->where("teacher_id",$id)
            ->where(function($query)use($date){
                if(!empty($date)){
                    $time = explode('-',$date);
                    $time = getStartAndEndUnixTimestamp($time[0],$time[1],$time[2]);
                    $query->where("create_time",">",$time['start'])->where("create_time","<",$time['end']);
                }})
            ->count();
        return json(['rows'=>$result,'total'=>$total]);
    }
    //查看作业详细信息
    public static function message()
    {
        $id = Request::instance()->only('id');
        return self::with("getClassName,getTeacherName,getPlanName")->where("id",$id['id'])->find();
    }


}